<?php

use api\app\model\MoneyLogModel;
use \Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use \AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest;
use api\app\model\CodeModel;

//签发token
function createToken($userId,$mobile)
{
    $data = [
        //签发人
        'iss' => request()->domain(),
        //签发时间
        'iat' => time(),
        //自定义数据
        'data' =>[
            'user_id' => $userId,
            'mobile' => $mobile
        ]
    ];
    //自定义key
    $key = config('app.jwt_key');
    // halt($key);
    $token = \Firebase\JWT\JWT::encode($data,$key,'HS256');
    return $token;
}

//检查验证码是否正确
function checkCode($mobile,$code)
{
    $data = CodeModel::where('mobile',$mobile)->find();
    if (!$data){
        return false; // error('请发送验证码');
    }
    if ($code != $data['code'] ){
        return false; // error('验证码不正确');
    }
    if (time() - $data['create_time'] > 1200000000){
        CodeModel::where('mobile',$mobile)->delete();
        return false; //error('验证码超时，请重新发送');
    }else{
        CodeModel::where('mobile',$mobile)->delete();
        return true;
    }

}

//发送验证码
function SendCode($mobile)
{
    CodeModel::where('mobile',$mobile)->delete();
    $code = mt_rand(1111, 9999);
    $config = new Config([
        // 从阿里云获取
        'accessKeyId' => config('app.code.accessKeyId'),
        'accessKeySecret' => config('app.code.accessKeySecret'),
    ]);

    $config->endpoint = "dysmsapi.aliyuncs.com";
    $client = new Dysmsapi($config);

    // 运行时参数超时设置，仅对使用了该运行时参数实例的请求有效
    $runtimeOptions = new RuntimeOptions();
    // true 忽略证书校验
    $runtimeOptions->ignoreSSL = true;

    $sendSmsRequest = new SendSmsRequest();
    // 手机号
    $sendSmsRequest->phoneNumbers = $mobile;
    // 签名名称
    $sendSmsRequest->signName = config('app.code.signName');
    // 模板CODE
    $sendSmsRequest->templateCode =  config('app.code.sms');
    // 生成随机数作为验证码
    $sendSmsRequest->templateParam = json_encode(['code' => $code]);
    try {
        $response = $client->sendSmsWithOptions($sendSmsRequest, $runtimeOptions);
    } catch (\Exception $exception) {
        halt($exception->getMessage());
    }
    $Smscode = new CodeModel();
    $Smscode->mobile = $mobile;
    $Smscode->code = $code;
    $Smscode->create_time = time();
    $Smscode->save();
    if ($response->body->code == 'OK') {
        return json([
            'code' => 1,
            'msg' => '短信发送成功',
            'data' => null
        ]);
    }else{
        return json([
            'code' => 0,
            'msg' => '短信发送失败',
            'data' => null
        ]);
    }
}

//余额记录
function addMoneyLog($userId,$money,$reason,$before,$type) {
    if ($type == 1) {
        $after = $before + $money;
    }
    if ($type == 0) {
        $after = $before - $money;
    }
    $addLog = [

        'user_id' => $userId,
        'money' => $money,
        'reason' => $reason,
        'before' => $before,
        'after' => $after,
        'type' => $type,
        'create_time' => date('Y-m-d H:i:s'),
    ];
    $add = MoneyLogModel::create($addLog);
    if ($add) {
        return true;
    }else{
        return false;
    }
}

//api接口url
function curlRequest($type, $url, $contentType, $data = [], $timeout = 60)
{
    try {
        $type = strtoupper($type);
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url); // 设置请求链接
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 不直接输出页面
        curl_setopt($curl, CURLOPT_HEADER, 0); // 获取响应头向下
        curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);   // 请求超时时间，单位：秒
        curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1');
        if (substr($url, 0, 5) == 'https') {
            // 自动判断是否是 https 提交
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
            // https请求，不验证证书和 hosts
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        }
        // 判断 Content-Type 类型
        if ($contentType == 'json') {
            curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type:application/json']);
        }
        if ($contentType == 'form') {
            curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type:application/x-www-form-urlencoded']);
        }
        switch ($type) {
            case "GET" :
                curl_setopt($curl, CURLOPT_HTTPGET, true);
                curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
                break;
            case "POST":
                curl_setopt($curl, CURLOPT_POST, true);
                if ($contentType == 'json') {
                    curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
                }
                if ($contentType == 'form') {
                    curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
                }
                break;
        }
        $result = curl_exec($curl);
        $err_code = curl_errno($curl);
        $curlInfo = curl_getinfo($curl);
        curl_close($curl);
        if ($err_code) {
            return ['status' => 'error', 'msg' => 'sendRequestError:' . $err_code];
        }
        if ($curlInfo['http_code'] == 200) {
            return json_decode($result, true);
        }
        return false;
    } catch (\Exception $e) {
        return ['status' => 'error', 'msg' => $e->getMessage()];
    }
}
